package com.module.framework.utils;

import com.module.framework.domain.Product;
import com.module.framework.vo.ProductListVO;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author JiHuiQin
 * @Date 2022/2/12 20:18
 * @Version 1.0
 */
public class BeanCopyUtils {

	private BeanCopyUtils() {

	}

	/**
	 * 对象拷贝
	 *
	 * @param source
	 * @param clazz
	 * @param <V>
	 * @return
	 */
	public static <V> V copyBean(Object source, Class<V> clazz) {
		V result = null;
		try {
			result = clazz.newInstance();
			BeanUtils.copyProperties(source, result);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 列表拷贝
	 *
	 * @param list
	 * @param clzz
	 * @param <V>
	 * @return
	 */
	public static <O, V> List<V> copyBeanList(List<O> list, Class<V> clzz) {
		return list.stream()
				.map(o -> copyBean(o, clzz))
				.collect(Collectors.toList());
	}

	/**
	 * 测试，使用
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		Product product = new Product();
		product.setId(1);
		product.setName("ddd");
		ProductListVO productListVO = copyBean(product, ProductListVO.class);
		System.out.println(productListVO);

	}
}
